<?php
/**
 * Extension of PHPCake HtmlHelper
 */
class ExtendHelpers{   
   
    public static function css($path, $options = array()) {
        if (!is_array($path)) {
            if (isset($this->_includedStyleSheets[$path])) {
                return null;
            }
        }
        $this->_includedStyleSheets[$path] = true;
        return parent::css($path, $options);
    }

    public static function cmsButton( $name , $link , $imageUrl, $type , $options = null){
                if( $type=='link' ){
                    $image = CHtml::image($imageUrl, $name, array()).'</br>'.$name;  
                    $onclick = null;
                }else{                    
                    if($options['type']==2){
                        $image = CHtml::image($imageUrl, $name).'</br>'.$name;
                        $onclick = array('onclick' => 'OnSubmitForm2("'.$link.'")');
                    }else{
                         $image = CHtml::image($imageUrl, $name).'</br>'.$name;
                          $onclick = array('onclick' => 'OnSubmitForm("'.$link.'")');
                    }                    
                }                
		$xhtml = $type=='link'? CHtml::link( $image, array( $link )) : CHtml::link( $image, '#', $onclick);
		return '<div class="toolbar-button">'.$xhtml.'</div>';
	}

    public static function cmsLink($name, $path, $options = array(), $type = 'link') {
        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        $options = array_diff_key($options, array('fullBase' => null, 'pathPrefix' => null));

        if (!isset($options['alt'])) {
            $options['alt'] = '';
        }

        $url = false;
        if (!empty($options['url'])) {
            $url = $options['url'];
            unset($options['url']);
        }

        $image = $name;


        if ($type == 'link') {
            return '<div class="toolbar-button" >' . sprintf($this->_tags['link'], $this->url($url), null, $image) . '</div>';
        } else {
            return '<div class="toolbar-button" >' . sprintf($this->_tags['link'], '#', "onclick = " . "OnSubmitForm('" . $this->url($url) . "')", $image) . '</div>';
        }

        return $image;
    }

    public static function cmsLinkSort($name, $column, $ssFilter, $path, $options = array(), $order = 'DESC') {
        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        $options = array_diff_key($options, array('fullBase' => null, 'pathPrefix' => null));

        if (!isset($options['alt'])) {
            $options['alt'] = '';
        }

        $url = false;
        if (!empty($options['url'])) {
            $url = $options['url'];
            unset($options['url']);
        }

        $iconSort = '';
        if ($ssFilter['col'] != $column) {
            $url['col'] = $column;
            $url['order'] = $order;
            $iconSort = '';
            $options['title'] = __('Click to order');
        } else {
            $sortOrder = '';
            if ($ssFilter['order'] == 'DESC') {
                $sortOrder = 'ASC';
                $iconSort = sprintf($this->_tags['image'], $path . '/sort_desc.png', $this->_parseAttributes($options, null, '', ' '));
                $options['title'] = __('Sort ASC');
            } else {
                $sortOrder = 'DESC';
                $iconSort = sprintf($this->_tags['image'], $path . '/sort_asc.png', $this->_parseAttributes($options, null, '', ' '));
                $options['title'] = __('Sort DESC');
            }
            $url['col'] = $column;
            $url['order'] = $sortOrder;
        }

        $title = FALSE;
        if (!empty($options['title'])) {
            $title = $options['title'];
            unset($options['title']);
        }
        $image = $name . ' ' . $iconSort;

        if ($url) {
            if ($title)
                return sprintf($this->_tags['link'], $this->url($url), 'title = "' . $title . '"', $image);
            return sprintf($this->_tags['link'], $this->url($url), NULL, $image);
        }
        return $image;
    }

    public static function cmsLinkOnOff($name, $column, $ssFilter, $path, $options = array(), $order = 'off') {
        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        $options = array_diff_key($options, array('fullBase' => null, 'pathPrefix' => null));
        if (!isset($options['alt'])) {
            $options['alt'] = '';
        }

        $url = false;
        if (!empty($options['url'])) {
            $url = $options['url'];
            unset($options['url']);
        }

        $iconSort = '';
        $sortOrder = '';
        if ($ssFilter['order'] == 'off') {
            $sortOrder = 'on';
            $iconSort = sprintf($this->_tags['image'], $path . '/sort_desc.png', $this->_parseAttributes($options, null, '', ' '));
            $options['title'] = __('Turn on');
        } else {
            $sortOrder = 'off';
            $iconSort = sprintf($this->_tags['image'], $path . '/sort_asc.png', $this->_parseAttributes($options, null, '', ' '));
            $options['title'] = __('Turn off');
        }
        $url['col'] = $column;
        $url['order'] = $sortOrder;

        $title = FALSE;
        if (!empty($options['title'])) {
            $title = $options['title'];
            unset($options['title']);
        }
        $image = ( $sortOrder == 'on') ? $name . __('on') : $name . __('off');
        if ($url) {
            if ($title)
                return sprintf($this->_tags['link'], $this->url($url), 'title = "' . $title . '"', $image);
            return sprintf($this->_tags['link'], $this->url($url), NULL, $image);
        }
        return $image;
    }

    public static function menu($items, $options = array()) {
        $output = '';
        foreach ($items as $item) {
            if (isset($item['url']) && isset($item['text'])) {
                $url = $item['url'];
                $text = $item['text'];
                unset($item['url']);
                unset($item['text']);
                $extra_classes = '';
                if (isset($url['controller'])) {
                    if ($url['controller'] == $this->params['controller']) {
                        $extra_classes = 'active';
                    }
                } else {
                    $extra_classes = 'active';
                }
                $item['class'] = isset($item['class']) ? $item['class'] . ' ' . $extra_classes : $extra_classes;
                $output .= sprintf($this->_tags['li'], $this->_parseAttributes($item), $this->link($text, $url));
            }
        }
        return sprintf($this->_tags['ul'], $this->_parseAttributes($options), $output);
    }

    public static function format_text_content($content) {
        return str_replace("\n", "<br />", $this->make_clickable(h($content)));
    }

    public static function make_clickable($ret) {
        $ret = ' ' . $ret;
        // in testing, using arrays here was found to be faster
        $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))+)#is', array($this, '_make_url_clickable_cb'), $ret);
        $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', array($this, '_make_web_ftp_clickable_cb'), $ret);
        $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', array($this, '_make_email_clickable_cb'), $ret);
        // this one is not in an array because we need it to run last, for cleanup of accidental links within links
        $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
        $ret = trim($ret);
        return $ret;
    }

    private static function _make_url_clickable_cb($matches) {
        $url = $matches[2];
        if (empty($url))
            return $matches[0];
        return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>";
    }

    private static function _make_web_ftp_clickable_cb($matches) {
        $ret = '';
        $dest = $matches[2];
        $dest = 'http://' . $dest;
        if (empty($dest))
            return $matches[0];
        // removed trailing [,;:] from URL
        if (in_array(substr($dest, -1), array('.', ',', ';', ':')) === true) {
            $ret = substr($dest, -1);
            $dest = substr($dest, 0, strlen($dest) - 1);
        }
        return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
    }

    private static function _make_email_clickable_cb($matches) {
        $email = $matches[2] . '@' . $matches[3];
        return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
    }

    public static function on_time($item, $visitor) {
        $time = round($item / $visitor);
        echo gmdate("H:i:s", $time);
    }

    public static function get_value_div($a, $b) {
        if ($b == 0)
            return 0;
        return substr(( $a * 100 / $b), 0, 4).'%';
    }

    public static function get_num_div($a, $b) {
        if ($b == 0)
            return 0;
        return substr(( $a / $b), 0, 4);
    }
    private static function _parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
        if (!is_string($options)) {
            $options = (array) $options + array('escape' => true);

            if (!is_array($exclude)) {
                $exclude = array();
            }

            $exclude = array('escape' => true) + array_flip($exclude);
            $escape = $options['escape'];
            $attributes = array();

            foreach ($options as $key => $value) {
                if (!isset($exclude[$key]) && $value !== false && $value !== null) {
                    $attributes[] = self::_formatAttribute($key, $value, $escape);
                }
            }
            $out = implode(' ', $attributes);
        } else {
            $out = $options;
        }
        return $out ? $insertBefore . $out . $insertAfter : '';
    }

}
